<template>
  <el-dialog title="选择图片" custom-class="imgLibDialog" v-model="show" width="90%" :append-to-body="true"
             :close-on-click-modal="true">
    <div class="dialog_center imgLib">
      <div class="imgLib_group">
        <div class="imgLib_group_search">
          <el-input v-model="searchGroupName" size="small" placeholder="搜索分组" clearable></el-input>
          <el-popover
              placement="bottom"
              v-model:visible="showGroupProp"
              :width="200">
            <el-input placeholder="请输入分组名称" v-model="groupName" clearable></el-input>
            <div style="text-align: right; margin-top: 10px;">
              <el-button size="mini" type="text" @click="showGroupProp = false">取消</el-button>
              <el-button type="primary" size="mini" @click="addGroup()" v-loading="addGroupLoading">确定</el-button>
            </div>
            <template #reference>
              <el-button size="small" type="primary" icon="el-icon-plus"
                         style="margin-left: 10px;padding: 9px;height: 32px"></el-button>
            </template>
          </el-popover>
        </div>
        <div class="imgLib_group_list" v-loading="groupLoading">
          <div class="imgLib_group_list_span" v-show="!searchGroupName || '全部图片'.includes(searchGroupName)" v-on:click="activeGroupId=null" :class="null === activeGroupId ? 'is-active' : ''">
            <i class="vbl " :class="activeGroupId===null?'vbl-wenjianjia':'vbl-wenjianjia1'"></i>
            <div class="imgLib_group_list_span_name">全部图片</div>
          </div>
          <div class="imgLib_group_list_span" v-show="!searchGroupName || '未分组'.includes(searchGroupName)" v-on:click="activeGroupId='none'" :class="'none' === activeGroupId ? 'is-active' : ''">
            <i class="vbl " :class="activeGroupId==='none'?'vbl-wenjianjia':'vbl-wenjianjia1'"></i>
            <div class="imgLib_group_list_span_name">未分组</div>
          </div>
          <div class="imgLib_group_list_span" v-for="item in groupList" v-show="!searchGroupName || item.label.includes(searchGroupName)" v-bind:key="item.groupId" v-on:click="activeGroupId=item.groupId" :class="item.groupId === activeGroupId ? 'is-active' : ''">
            <i class="vbl " :class="activeGroupId===item.groupId?'vbl-wenjianjia':'vbl-wenjianjia1'"></i>
            <div class="imgLib_group_list_span_name">
              <el-input v-model="item.label" size="small" @blur="updateGroup(item)" :ref="item.groupId"
                        :disabled="updateGroupId !== item.groupId"></el-input>
            </div>
            <div class="imgLib_group_list_span_btn">
              <div class="b el-icon-edit-outline" v-on:click="updateGroupId=item.groupId"></div>
              <div class="b d el-icon-delete-solid" v-on:click="deleteGroup(item)"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="imgLib_list">
        <div class="imgLib_list_top">
          <div class="imgLib_list_top_tool">
<!--            <div class="imgLib_list_top_tool_span">-->
<!--              <el-select size="mini" style="width: 100px" v-model="sortType">-->
<!--                <el-option label="名称" :value="1"></el-option>-->
<!--                <el-option label="大小" :value="2"></el-option>-->
<!--                <el-option label="上传时间" :value="3"></el-option>-->
<!--              </el-select>-->
<!--            </div>-->
            <div class="imgLib_list_top_tool_span showType">
              <div class="showType_span vbl vbl-list" :class="showType === 'list'?'is-active':''" v-on:click="showType='list'"></div>
              <div class="showType_span vbl vbl-biaoge" :class="showType === 'grid'?'is-active':''" v-on:click="showType='grid'"></div>
            </div>
            <div class="imgLib_list_footer" v-if="isEdit">
              <div class="imgLib_list_footer_model">
                <el-button size="small" icon="el-icon-edit-outline" style="color: var(--danger)" type="text" v-on:click="isEdit = false">退出编辑模式</el-button>
              </div>
              <div class="imgLib_list_footer_checkAkk"><el-checkbox v-model="isCheckAll" @change="toggleImg"></el-checkbox> 全选</div>
              <div class="imgLib_list_footer_count">已选择{{ selectIdList.length }}张</div>
              <div class="imgLib_list_footer_btn">
                <el-tooltip effect="dark" content="修改分组" placement="top">
                  <el-button size="mini" type="text" icon="vbl vbl-yidong1" :disabled="selectIdList.length <= 0" @click="showChooseGroup=true;changeGroupId=null"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="删除图片" placement="top">
                  <el-button size="mini" type="text" icon="vbl vbl-shanchu1" :disabled="selectIdList.length <= 0" v-on:click="deleteImage"></el-button>
                </el-tooltip>
              </div>
            </div>
            <div class="imgLib_list_footer" v-else>
              <div class="imgLib_list_footer_model">
                <el-button size="small" icon="el-icon-edit-outline" type="text" v-on:click="isEdit = true">开启编辑模式</el-button>
              </div>
            </div>
          </div>
          <div class="imgLib_list_top_btn">
            <el-dropdown trigger="click">
              <el-button size="mini" type="primary" v-loading="uploadLoading" :disabled="uploadLoading">
                上传图片<i class="el-icon-arrow-down el-icon--right"></i></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-upload action='' :show-file-list='false' :auto-upload='false'
                               :on-change='uploadImg' accept="image/png, image/bmp, image/jpg, image/jpeg">
                      <div><i class="el-icon-plus"></i>直接上传</div>
                    </el-upload>
                  </el-dropdown-item>
                  <el-dropdown-item disabled icon="el-icon-circle-plus">剪切上传</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div class="imgLib_list_center" :class="showType" v-loading="loading">
          <template v-if="imgList.length">
            <template v-if="showType === 'grid'">
              <div class="imgSpan" v-for="item in imgList" v-bind:key="item.id" v-on:click="clickItem(item)" :class="selectIdList.indexOf(item.id)>-1?'is-active':''">
                <div class="imgSpan_top">
                  <img :src="baseUrl + item.filePath" />
                  <div class="imgSpan_top_check" v-if="isEdit">
                    <el-checkbox v-model="item.selected"></el-checkbox>
                  </div>
                  <i v-else class="select-icon el-icon-success" v-if="item.selected"></i>
                  <div class="imgSpan_top_ext">{{item.ext}}</div>
                  <div class="imgSpan_bottom">{{parseFloat(item.property?.B / 1024).toFixed(0)}}kb</div>
                </div>
                <div class="imgSpan_label">{{item.name}}</div>
              </div>
            </template>
            <template v-else-if="showType === 'list'">
                <el-table :data="imgList" @cell-click="clickItem">
                  <el-table-column width="40" align="center">
                    <template #default="scope">
                      <el-checkbox v-model="scope.row.selected" v-if="isEdit" style="pointer-events: none;"></el-checkbox>
                      <template v-else>
                        <i class="el-icon-success" v-if="scope.row.selected" style="color: var(--primary);font-size: 20px;"></i>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="date" label="图片" width="100" align="center">
                    <template #default="scope">
                      <div class="tableImage">
                        <img :src="baseUrl + scope.row.filePath" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="名称"></el-table-column>
                  <el-table-column prop="date" label="尺寸" width="150" align="center">
                    <template #default="scope">
                      {{scope.row?.property?.w}} * {{scope.row?.property?.h}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="property.B" label="大小" width="100" align="center">
                    <template #default="scope">
                      {{parseFloat(scope.row?.property?.B / 1024).toFixed(0)}}kb
                    </template>
                  </el-table-column>
                  <el-table-column prop="ext" label="类型" width="100" align="center"></el-table-column>
                  <el-table-column prop="createTime" label="上传时间" width="100" align="center">
                    <template #default="scope">
                      {{ $vbUtils.formatDate(scope.row.createTime, "YYYY-MM-DD") }}
                    </template>
                  </el-table-column>
                </el-table>
            </template>
          </template>
          <div class="empty" v-else>
            <img src="../../../img/ch/e98.png"/>
            <div class="">暂无图片~</div>
          </div>
        </div>
        <div class="imgLib_list_footer">
          <el-pagination @size-change="pageSizeChange" @current-change="getImgList" :current-page="pageConfig.pageIndex"
                         :page-sizes="[10, 20, 50, 100, 200]" :page-size="20" layout="total, sizes, prev, pager, next, jumper"
                         :pager-count="5" :total="pageConfig.total">
          </el-pagination>
          <div class="imgLib_list_footer_btn" v-if="!isEdit">
            <el-button size="small" v-on:click="close">取消</el-button>
            <el-button size="small" type="primary" :disabled="selectIdList.length <= 0" v-on:click="onConfirm">选择</el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
  <el-dialog title="修改图片分组" v-model="showChooseGroup" :append-to-body="true" :close-on-click-modal="true" top="35vh" width="360px">
    <el-select size="small" v-model="changeGroupId" placeholder="请选择分组" style="width: 100%">
      <el-option label="未分组" value="none" v-if="activeGroupId !== 'none'"></el-option>
      <el-option v-for="group in groupList" :key="group.groupId" :label="group.label" :value="group.groupId" v-show="group.groupId !== activeGroupId"></el-option>
    </el-select>
    <template #footer>
      <el-button size="small" v-on:click="showChooseGroup=false">取消</el-button>
      <el-button size="small" type="primary" :disabled="!changeGroupId" v-on:click="updateImgGroup">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>

export default {
  components: {
  },
  props: {
    width: {type: Number, default: 100},
    height: {type: Number, default: 100}
  },
  emits: ['onSelect'],
  data() {
    return {
      show: false,
      showChooseGroup: false,
      pageConfig: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      loading: true,
      showGroupProp: false,
      groupName: null,
      searchGroupName: null,
      addGroupLoading: false,
      groupLoading: true,
      uploadLoading: false,
      updateGroupId: null,
      imgList: [],
      activeGroupId: null,
      changeGroupId: null,
      baseUrl: null,
      sortType: 3,            // 排序模式 默认时间
      showType: "grid",       // 展示方式，默认宫格
      isEdit: false,          // 编辑状态
      selectIdList: [],       // 选择项
      groupList: []
    }
  },
  computed: {
    /**
     * 计算属性的 getter
     */
    isCheckAll () {
      let unCheck = this.imgList.some(data => {
        return !data.selected
      });
      return !unCheck
    }
  },
  mounted() {
  },
  methods: {
    /**
     * 打开对话框
     */
    open(param = {}) {
      this.show = true;
      this.loading = true
      this.showGroupProp = false
      this.groupName = null
      this.addGroupLoading = false
      this.groupLoading = true
      this.uploadLoading = false
      this.updateGroupId = null
      this.imgList = []
      this.activeGroupId = null
      this.baseUrl = null
      this.sortType = 3
      this.showType = "grid"
      this.isEdit = false
      this.selectIdList = []
      this.initIndex = param.index
      this.getGroup()
      this.getImgList()
    },

    /**
     * 关闭对话框
     */
    close() {
      this.show = false;
    },

    /**
     * 获取图片分组列表
     */
    getGroup() {
      let self = this
      this.groupLoading = true;
      this.$api.getImgLibraryGroup().then(res => {
        self.groupList = res.data || [];
        self.groupLoading = false;
      })
    },

    /**
     * 创建新分组
     */
    addGroup() {
      let self = this
      if (!this.groupName) {
        this.$message.error("分组名称不能为空")
        return
      }
      this.addGroupLoading = true
      this.$api.addImgLibraryGroup({label: this.groupName}).then(() => {
        self.getGroup();
        self.addGroupLoading = false
        self.showGroupProp = false
        this.groupName = null
      }).catch(() => {
        self.addGroupLoading = false
      })
    },

    /**
     * 更新分组
     *
     * @param item
     */
    updateGroup(item) {
      let self = this
      if (!item.label) {
        this.$message.error("分组名称不能为空")
        return
      }

      self.groupLoading = true
      self.$api.updateImgLibraryGroup({
        groupId: item.groupId,
        label: item.label
      }).then(() => {
        self.getGroup();
        self.groupLoading = false
        self.updateGroupId = null
      }).catch(() => {
        self.groupLoading = false
      })
    },

    /**
     * 删除分组
     *
     * @param item 删除对象
     */
    deleteGroup(item) {
      let self = this
      this.$confirm('此操作将把分组内的图片转移至未分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.groupLoading = true;
        self.$api.deleteImgLibraryGroup({
          groupId: item.groupId
        }).then(() => {
          this.activeGroupId = null;
          self.getGroup();
          self.groupLoading = false;
        })
      })
    },

    /**
     * 获取图片列表
     */
    getImgList(index) {
      let self = this
      if (index) this.pageConfig.pageIndex = index;

      self.loading = true
      this.$api.getImgLibraryList({
        groupId: this.activeGroupId==='none' ? null : this.activeGroupId,
        noGroup: this.activeGroupId==='none',
        pageIndex: this.pageConfig.pageIndex - 1,
        pageSize: this.pageConfig.pageSize
      }).then(res => {
        res.data.forEach(item => {
          item.selected = false
        });
        self.imgList = res.data || [];
        self.baseUrl = res.baseUrl;
        self.pageConfig.total = res.total;
        self.loading = false
      })
    },

    pageSizeChange(size) {
      this.pageConfig.pageSize = size;
      this.getImgList(1);
    },

    /**
     * 上传图片
     *
     * @param file
     */
    uploadImg(file) {
      let self = this
      self.uploadLoading = true;
      this.$api.uploadImgLibrary({
        file: file.raw,
        groupId: self.activeGroupId==='none' ? null : self.activeGroupId
      }).then(() => {
        self.getImgList(1);
        self.uploadLoading = false;
        self.$message.success("上传成功")
      })
    },

    /**
     * 选择图片
     *
     * @param item
     */
    clickItem(item) {
      let odSelected = item.selected
      if (!this.isEdit) {
        this.imgList.forEach(img => {
          img.selected = false
        })
      }
      item.selected = !odSelected
    },

    /**
     * 选择/取消图片
     */
    toggleImg(check) {
      this.imgList.forEach(img => {
        img.selected = check
      })
    },

    /**
     * 删除图片
     */
    deleteImage() {
      let self = this
      this.$confirm('此操作将会将图片永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.$api.deleteImages({
          targetList: self.selectIdList
        }, {
          loading: true
        }).then(res => {
          self.$message.success("删除成功!");
          self.getImgList();
        })
      })
    },

    /**
     * 更新图片分组
     */
    updateImgGroup() {
      this.$api.moveImagesGroup({
        groupId: this.changeGroupId==='none' ? null : this.changeGroupId,
        targetList: this.selectIdList
      }, {
        loading: true
      }).then(res => {
        this.showChooseGroup = false;
        this.$message.success("修改成功!");
        this.getImgList();
      })
    },

    /**
     * 选择图片
     */
    onConfirm () {
      let self = this
      let selectItem = this.imgList.find(item => {
        return self.selectIdList.indexOf(item.id) >-1
      })
      if (selectItem) {
        self.$emit("onSelect", {
          id: selectItem.id,
          url: self.baseUrl + selectItem.filePath,
          index: self.initIndex
        })
      }
      self.close()
    }
  },
  watch: {
    activeGroupId: function () {
      this.pageConfig.pageIndex = 1;
      return this.getImgList();
    },
    updateGroupId: function () {
      let self = this
      if (this.updateGroupId) {
        try {
          self.$nextTick(() => {
            self.$refs[self.updateGroupId].focus()
          })
        } catch (e) {
        }
      }
    },
    imgList: {
      handler: function (){
        let selectIdList = []
        this.imgList.forEach(item => {
          if (item.selected) selectIdList.push(item.id)
        })
        this.selectIdList = selectIdList
      },
      deep: true
    },
    isEdit: function () {
      this.selectIdList = []
      this.imgList.forEach(item => {
        item.selected = false
      })
    }
  }
}
</script>
<style scoped lang="scss">
.imgLib {
  width: 100%;
  display: flex;
  height: 80vh;

  .imgLib_group {
    width: 220px;
    height: 100%;
    border-right: 1px solid var(--border-bd);
    display: flex;
    flex-direction: column;
    position: relative;
    flex-shrink: 0;

    .imgLib_group_search {
      display: flex;
      align-items: center;
      padding: 0 15px;
    }

    .imgLib_group_list {
      flex: 1;
      padding-top: 10px;
      overflow: auto;

      .imgLib_group_list_span {
        height: 35px;
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 0px 15px;

        &:hover,
        &.is-active {
          background: var(--bg-page);
          :deep(input){
            color: var(--primary) !important;
          }
          .imgLib_group_list_span_btn {
            display: flex;
          }
          i{
            color: var(--warning);
          }
        }

        &.is-active{
        }

        i {
          margin-right: 10px;
          color: var(--font-hc);
        }

        .imgLib_group_list_span_name {
          width: calc(100% - 60px);
          font-size: 12px;

          :deep(input) {
            border: 0;
            background: transparent;
            color: var(--font-hb) !important;
            cursor: pointer;
            border-bottom: 1px solid var(--primary);
            border-radius: 0;
            padding-left: 0;
          }

          :deep(.el-input) {
            &.is-disabled {
              input {
                border: 0 !important;
              }
            }
          }
        }

        .imgLib_group_list_span_btn {
          display: none;

          .b {
            width: 24px;
            text-align: right;
            cursor: pointer;
            color: var(--font-hc);

            &:hover {
              color: var(--primary);
            }

            &.d:hover {
              color: var(--danger);
            }
          }
        }
      }
    }
  }

  .imgLib_list {
    padding: 0 15px;
    display: flex;
    flex-direction: column;
    flex: 1;
    .imgLib_list_top{
      display: flex;
      align-items: center;
      .imgLib_list_top_tool{
        display: flex;
        align-items: center;
        flex: 1;
        .imgLib_list_top_tool_span{
          :deep(input){
            height: 28px;
            border-radius: 2px !important;
            border: 1px solid var(--border-bc);
          }
          :deep(.el-input--mini .el-input__icon){
            line-height: 26px !important;
          }
          height: 28px;
          border-radius: 2px;
          margin-right: 10px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          &.showType{
            border-radius: 2px;
            border: 1px solid var(--border-bc);
            .showType_span{
              width: 34px;
              text-align: center;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              &.is-active{
                background: var(--bg-page);
                color: var(--primary);
              }
            }
          }
        }
      }
      .imgLib_list_top_btn{
      }
    }
    .imgLib_list_center{
      flex: 1;
      position: relative;
      overflow: auto;
      margin-top: 10px;
      &.grid{
        display: flex;
        flex-flow: wrap row;
        align-content: flex-start;
        gap: 10px;
        .imgSpan{
          box-sizing: border-box;
          height: 170px;
          width: 140px;
          cursor: pointer;
          &:hover{
            .imgSpan_top {
              border: 2px solid var(--primary);
            }
          }
          &.is-active{
            .imgSpan_top {
              border: 2px solid var(--primary);
              position: relative;
              &:before{
                content: "";
                background-color: rgba(41, 141, 248, 0.2);
                width: 100%;
                height: 100%;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 1;
              }
            }
          }
          .imgSpan_top{
            width: 140px;
            height: 140px;
            box-sizing: border-box;
            position: relative;
            display: flex;
            -webkit-box-align: center;
            align-items: center;
            -webkit-box-pack: center;
            justify-content: center;
            background-image: url("../../../img/clear1.png");
            background-color: rgb(242, 242, 242);
            transition: all 0.15s ease-in-out 0s;
            border: 2px solid #ecf5ff;
            border-radius: 3px;
            img{
              max-width: 100%;
              max-height: 100%;
              position: relative;
              z-index: 2;
              pointer-events: none;
            }
            .select-icon {
              color: var(--primary);font-size: 20px;
              position: absolute;
              top: 2px;
              left: 2px;
              z-index: 100;
            }
            .imgSpan_top_check{
              position: absolute;
              top: 2px;
              left: 5px;
              z-index: 4;
              pointer-events: none;
              :deep(.el-checkbox__inner){
                transform: scale(1.2);
              }
            }
            .imgSpan_top_ext{
              position: absolute;
              top: 0;
              right: 0;
              background: #f9f9f9;
              font-size: 12px;
              color: #000;
              border-radius: 0 0 0 4px;
              z-index: 3;
              padding: 0 5px;
              line-height: 15px;
              height: 20px;
            }
            .imgSpan_bottom{
              position: absolute;
              bottom: 0;
              right: 0;
              background: #f9f9f9;
              font-size: 12px;
              color: #000;
              border-radius: 4px 0 0 0;
              z-index: 3;
              padding: 0 5px;
              line-height: 15px;
              height: 20px;
            }
          }
          .imgSpan_label{
            height: 30px;
            line-height: 30px;
            font-size: 12px;
            text-align: center;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
      :deep(.tableImage){
        width: 70px;
        height: 70px;
        position: relative;
        display: flex;
        -webkit-box-align: center;
        align-items: center;
        -webkit-box-pack: center;
        justify-content: center;
        border-radius: 3px;
        background-image: url("../../../img/clear1.png");
        background-color: rgb(242, 242, 242);
        transition: all 0.15s ease-in-out 0s;
        img{
          max-width: 100%;
          max-height: 100%;
          position: relative;
          z-index: 2;
          pointer-events: none;
        }
      }
    }
    .imgLib_list_footer{
      display: flex;
      height: 50px;
      align-items: center;
      .imgLib_list_footer_model{
        margin-right: 10px;
        cursor: pointer;
      }
      .imgLib_list_footer_checkAkk{
        margin-right: 10px;
        font-size: 12px;
        display: flex;
        align-items: center;
        position: relative;
        z-index: 4;
        :deep(.el-checkbox__inner){
          margin-right: 5px;
        }
      }
      .imgLib_list_footer_count{
        font-size: 12px;
        color: var(--font-hc);
        min-width: 65px;
      }
      .imgLib_list_footer_btn{
        flex: 1;
        text-align: right;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        :deep(button){
          i{
            font-size: 24px;
          }
        }
        .icon{
          width: 35px;
          cursor: pointer;
          &:hover{
            color: var(--primary);
          }
        }
      }
    }
  }

  .empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;

    img {
      width: 150px;
      opacity: 0.8;
    }

    div {
      font-size: 12px;
      margin-top: 10px;
      color: var(--font-hc);
    }
  }
}
</style>
